package chapter6.section4;

//程序6-4：一个实现了Comparable接口的Account类
import java.util.Arrays;

public class Account implements Comparable {
	private String id;// 账户id，唯一性的标识
	private String name;// 账户拥有人的姓名
	private int balance;// 余额

	public Account(String id, String name, int balance) {
		this.id = id;
		this.name = name;
		this.balance = balance;
	}  

	// 取款的方法,返回本次取出的金额，如果为0，表示余额不足
	public int withdraw(int amount) {
		int result = 0;
		if (this.balance >= amount) {
			this.balance = this.balance - amount;
			result = amount;
		}
		return result;
	}

	public int getBalance() {
		return this.balance;
	}

	public void setBalance(int balance) {
		this.balance = balance;
	}

	public String getId() {
		return id;
	}

	// toString方法覆盖了来自根类Object的方法
	@Override
	public String toString() {
		return "Account[id:" + id + ",name:" + name + ",balance:" + balance
				+ "]";
	}

	// compareTo方法覆盖了来自接口的方法
	@Override
	public int compareTo(Object o) {
		int result = 0;
		// 这里忽略了o的类型不是Account的情况
		Account t = (Account) o;
		// 利用字符串对象自身的compareTo方法作为账户大小的比较
		return this.id.compareTo(t.getId());
	}

	public static void main(String[] args) {
		Account[] accounts = new Account[5];
		accounts[0] = new Account("001", "王峰", 1000);
		accounts[1] = new Account("002", "张静", 1500);
		accounts[2] = new Account("004", "翟宇", 660);
		accounts[3] = new Account("003", "鲁宁", 800);
		accounts[4] = new Account("005", "刘新", 1700);
		Arrays.sort(accounts);
		for (int i = 0; i < accounts.length; i++) {
			System.out.println(accounts[i]);
		}
	}
}
